package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.behavior.service.IApBehaviorService;
import com.heima.behavior.util.ApUserThreadLocalUtil;
import com.heima.common.constants.BehaviorContstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Slf4j
@Service
@Transactional
public class ApBehaviorServiceImpl implements IApBehaviorService {

    @Resource
    private CacheService cacheService;

    /**
     * 用户点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likes(LikesBehaviorDto dto) {
        ApUser user = ApUserThreadLocalUtil.getUser();
        //判断是否登录
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //点赞操作，点赞或取消点赞
        short operation = dto.getOperation();
        Integer userId = user.getId();
        long articleId = dto.getArticleId();
        if (operation == 0) {
            /**
             * 点赞，先判断之前是否点赞
             */
            Object object =
                    cacheService.hGet(BehaviorContstants.LIKE_BEHAVIOR + articleId, userId.toString());
            if (object != null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已点赞");
            }
            log.info("用户{}点赞文章{}，{}", userId, articleId, dto);
            //保存至Redis
            cacheService.hPut(BehaviorContstants.LIKE_BEHAVIOR + articleId, userId.toString(), JSON.toJSONString(dto));
        } else {
            //取消点赞
            log.info("用户{}取消点赞文章{}，{}", userId, articleId, dto);
            cacheService.hDelete(BehaviorContstants.LIKE_BEHAVIOR + articleId, userId.toString());
        }

        return ResponseResult.okResult(null);
    }

    /**
     * 用户阅读
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        ApUser user = ApUserThreadLocalUtil.getUser();
        //判断是否登录
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        long articleId = dto.getArticleId();
        //阅读次数更新
        String readJson =
                (String) cacheService.hGet(BehaviorContstants.READ_BEHAVIOR + articleId, user.getId().toString());
        if (StringUtils.isNotBlank(readJson)) {
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(readJson, ReadBehaviorDto.class);
            dto.setCount(readBehaviorDto.getCount() + dto.getCount());
        }
        log.info("用户ID:{}, 用户阅读文章ID:{},内容:{}", user.getId(), dto.getArticleId(), dto);
        cacheService.hPut(BehaviorContstants.READ_BEHAVIOR + articleId, user.getId().toString(), JSON.toJSONString(dto));

        return ResponseResult.okResult(null);
    }

    /**
     * 用户不喜欢
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unlikes(UnLikesBehaviorDto dto) {
        ApUser user = ApUserThreadLocalUtil.getUser();
        //判断是否登录
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (dto.getType() == 0) {
            log.info("用户不喜欢，文章ID:{} ,用户ID:{}, 内容:{}", dto.getArticleId(), user.getId(), dto);
            cacheService
                    .hPut(BehaviorContstants.UN_LIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString(), JSON.toJSONString(dto));
        } else {
            log.info("用户取消不喜欢，文章ID:{} ,用户ID:{}, 内容:{}", dto.getArticleId(), user.getId(), dto);
            cacheService.hDelete(BehaviorContstants.UN_LIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString());
        }

        return ResponseResult.okResult(null);
    }
}
